<template>
    <div class="dataEdit">
      <div>
        <el-form :model="form" label-width="120px" size="small" label-position="left" :rules="rules">
            <el-form-item :label="filterType.title">
                <el-select v-model="form[filterType.field]" class="m-2" placeholder="请选择台账类型">
                    <el-option
                      v-for="(item,key) in filterType.options"
                      :key="key"
                      :label="item.label"
                      :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item v-if="formData" v-for="item in formData[form[filterType.field]]" :label="item[Style['title']]" :style="{width: item[Style['style']]?item[Style['style']]:'400px'}" :prop="item[Style['field']]">
                <el-input v-if="fieldsContrast[item[Style['field']]].componentID>0 && fieldsContrast[item[Style['field']]].componentType==5" v-model="form[item[Style['field']]]"
                      :disabled="fieldsContrast[item[Style['field']]].permission=='true'?true:false" placeholder="自动取得编号" >
                </el-input>
                <el-select v-if="fieldsContrast[item[Style['field']]].componentType==='down'" :disabled="fieldsContrast[item[Style['field']]].permission=='true'?true:false"
                         v-model="form[item[Style['field']]]" placeholder="下拉框" clearable>
                    <el-option v-for="(it,index) in combos[item[Style['field']]]" :value="it.value" :label="it.label"
                            :key="index"></el-option>
                </el-select>
                <el-input v-if="fieldsContrast[item[Style['field']]].componentType==='map'" placeholder="请点击选择..."  :readonly="fieldsContrast[item[Style['field']]].permission=='true'?false:true" type="text" v-model="form[item[Style['field']]]">
                    <template #append>
                    <el-button :disabled="item.editable===0" @click="clickMap(fieldsContrast[item[Style['field']]],form,item[Style['field']])"
                                :icon="Plus"/>
                    </template>
                </el-input>
                <el-input v-if="fieldsContrast[item[Style['field']]].componentType==='list'" placeholder="请点击选择..."  :readonly="fieldsContrast[item[Style['field']]].permission=='true'?true:false" type="text" v-model="form[item[Style['field']]]">
                    <template #append>
                    <el-button :disabled="item.editable===0" @click="showSource({item:fieldsContrast[item[Style['field']]],value:form[item[Style['field']]],target:form})"
                                :icon="Plus"/>
                    </template>
                </el-input>
                <el-input  v-model="form[item[Style['field']]]" v-if="fieldsContrast[item[Style['field']]].componentType==='text'&& fieldsContrast[item[Style['field']]].componentType!=5" :disabled="fieldsContrast[item[Style['field']]].permission=='true'?true:false" ></el-input>
                <el-date-picker
                    v-model="form[item[Style['field']]]"
                    type="datetime"
                    v-if="fieldsContrast[item[Style['field']]].componentType==='date'"
                    placeholder="请选择日期"
                    :disabled-date="disabledDate"
                    :shortcuts="shortcuts"
                />
                <el-form v-if="fieldsContrast[item[Style['field']]].componentType==='array'" :model="form[item[Style['field']]]=[]">
                    <div v-if="form[item[Style['field']]]" v-for="(t,indexb) in form[item[Style['field']]]" style="display: flex;">
                        <el-form-item v-for="v in fieldsContrast[item[Style['field']]].mapTypes" :label="v.name" style="margin-bottom: 10px;">
                            <el-select v-if="v.style=='select'" style="margin-right:10px;" v-model="form[item[Style['field']]][indexb][v.value]" class="m-2" placeholder="请选择">
                                <el-option
                                  v-for="(f,n) in v.option"
                                  :key="n"
                                  :label="f.label"
                                  :value="f.value"
                                />
                            </el-select>
                            <el-input v-if="v.style=='input'" style="margin-right:10px;" v-model="form[item[Style['field']]][indexb][v.value]"></el-input>
                        </el-form-item>
                        <el-button @click="form[item[Style['field']]].splice(indexb,1)">删除</el-button>
                        <el-button v-if="form[item[Style['field']]].length-1==indexb" @click="form[item[Style['field']]].push({})">新增</el-button>
                    </div>
                    <div v-if="form[item[Style['field']]].length==0"><el-button @click="form[item[Style['field']]]=[{}]">新增</el-button></div>
                </el-form>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="formSave" size="small" style="margin: 10px 10px 10px 0;">保存</el-button>
            </el-form-item>
        </el-form>
      </div>
        
        <DataGridSelect ref="DGE" :isequipment="true" @submit="getSourceData"></DataGridSelect>
        <el-dialog
      v-model="dialogMap"
      width="60%"
    ><locationmmap :mapType="mapType" @pushValue="weftWarp"></locationmmap></el-dialog>
    </div>
</template>
<script setup>
    import {ref, onMounted, watch} from "vue"
    import XEUtils from "xe-utils"
    import {editForm} from "/@/api/linkoo/form"
    import {useRoute, useRouter} from 'vue-router'
    import {typeFilter,typeData} from "/@/api/form/typeEdit"
    import {getDefault} from "/@/api/linkoo/form/index"
    import {Plus} from '@element-plus/icons-vue'
    import DataGridSelect from './select.vue'
    import locationmmap from "./locationmap.vue"
    import {ElMessage, ElMessageBox} from 'element-plus'
    let value = ref(null)
    let DGE = ref(null)
    let form = ref({})
    let rules = ref({})
    // 一下是真实数据
    const shortcuts = [
        {
            text: 'Today',
            value: new Date(),
        },
        {
            text: 'Yesterday',
            value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            return date
            },
        },
        {
            text: 'A week ago',
            value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            return date
            },
        },
    ]
    let formData = ref({})
    let template = ref(null)
    let filters = ref(null)
    let Style = ref(null)
    let TM = {}
    let fieldsContrast=ref({})//新类型与旧类型对比
    let combos = ref(null)//所有下拉值
    let fault = ref(null)
    let configList =ref(null)
    let filterType = ref({title:'',options:[]})
    const route = useRoute()
    const router = useRouter()
    let arr = ref([])
    onMounted(()=>{
        TM['CODE']=(route.path.split("/"))[2]
        typeData(TM['CODE']).then((res)=>{
            if(res.code===0){
                template.value=res.data
            }
        })
    })
    watch(()=>template.value,(data)=>{
        const tt= template.value.info[TM['CODE']]
        TM['ID']=tt.template['templateID']
        TM['MD']=XEUtils.find(tt.tables,item=>item.tableType===0).tableName

        const ft= template.value.info[tt.template.enterDirect]
        buildForm(tt)
        const ftb=XEUtils.find(ft.tables,item=>item.tableType===1)
        const tff= XEUtils.find(ft.tables,item=>item.tableType===0)
        Style.value=buildStyle(ftb.Fields)
        const FV= template.value.filterData
        buildFilter(FV,tff.Fields,ftb)
        filterType.value.title=tff.Fields[0].fieldDispName
        console.log(tff.Fields[1].fieldName)
        let WebFields = JSON.parse(data.info[TM['CODE']].template.FormCode)
        combos.value = data.info[TM['CODE']].combos
        
        let id = null
        WebFields.formData.mainList.forEach(element => {
            fieldsContrast.value[element.fieldName]={
                componentType:element.componentType,
                componentFieldID:element.componentFieldID,
                editable:element.editable,
                componentID:element.configID,
                tableID:element.tableID,
                componentFieldName:element.componentFieldName,
                permission:element.permission,
                mapvalue:element.mapvalue,
                mapTypes:element.mapTypes,
                configList:element.configList,
                width:element.width,
                configID:element.configID,
                required:element.required
            }
            // 数组类型的字符转JSON
            if(element.arrList){
                let str =JSON.stringify(element.arrList)
                fieldsContrast.value[element.fieldName]['mapTypes']=JSON.parse(element.arrList)
            }
            if(element.tableID){
                id=element.tableID
            }
        });
        XEUtils.objectEach(form.value,(valuet,keyt)=>{
            if(fieldsContrast.value[keyt]){
                rules.value[keyt]=[{ required:fieldsContrast.value[keyt].required, message: '必填项', trigger: 'blur' }]
            }
        })
        getDefaults(id)
    })
    const getSourceData = ({data}) => {
        console.log(data,configList.value);
        let objlist={}
        data.forEach((item)=>{
            XEUtils.objectEach(configList.value,(key,v)=>{
                console.log(item,key,v,key['v']);
                if(objlist[v]){
                    objlist[v]=objlist[v]+','+item[key['v']]
                }else{
                    objlist[v]=item[key['v']]
                }
            })
        })
        XEUtils.objectEach(objlist,(key,v)=>{
            console.log(key,v);
            form.value[v]=key
        })
        configList.value=null
    }
    const disabledDate = (time) => {
        return time.getTime() > Date.now()
    }
    const showSource=({item, value, target, ref})=>{
        console.log({field: item, value: value, data: form.value});
        configList.value=item.configList
        DGE.value.Data = Object.assign({}, {field: item, value: value, data: form.value})
        DGE.value.todo()
    }
    const getDefaults =(id)=>{
        getDefault(id).then(res => {
            if(res.code==0){
                XEUtils.objectEach(res.data, (item, key) => {
                    form.value[key] = item
                })
            }else{
                ElMessage({
                    message: '获取失败!',
                    type: 'error',
                })
            }
        })
    }
    let mapType = ref(null)
    let mapFilde = ref(null)
    let dialogMap = ref(false)
    const clickMap = (type,data,field)=>{
        console.log("地图",type,data,field);
        mapType.value=type
        mapFilde.value=field
        dialogMap.value=true
    }
    const weftWarp = (value)=>{
        console.log(value,mapFilde.value,mapType.value);
        if(mapType.value.mapTypes=="address"){
            form.value[mapFilde.value]=value[mapType.value.mapTypes]
            form.value[mapType.value.mapvalue]=value.lonlat
        }else{
            form.value[mapFilde.value]=value[mapType.value.mapTypes]
            form.value[mapType.value.mapvalue]=value.address
        }
        dialogMap.value=false
    }
    const buildFilter=(FV,tff,ftb)=>{
        const tp=tff[0].fieldName
        XEUtils.arrayEach(FV,item=>{
            filterType.value.options.push({label:item[tp],value:item[tp]})
            filterType.value.field=item[tff[1].fieldName]
            formData.value[item[tp]]=item['ChildTables'][ftb.tableName].map(row=>{
                if(XEUtils.toValueString(row[Style.value['expend']])!==''){
                    row[Style.value['expend']]=JSON.parse(row[Style.value['expend']])
                }
                return row
            })
        })
    }
    const buildForm=(tt)=>{
            XEUtils.arrayEach(tt.tables[0].Fields,ff=>{
            form.value[ff.fieldName]=null
        })
    }

    const buildStyle=(tfv)=>{
        const style={}
            XEUtils.arrayEach(tfv,ff=>{
            switch (ff.fieldDispName){
                case "字段名称":
                    style["field"]=ff.fieldName
                    break
                case "字段说明":
                    style["title"]=ff.fieldName
                    break
                case "字段类型":
                    style["type"]=ff.fieldName
                    break
                case "字段样式":
                    style["style"]=ff.fieldName
                    break
                case "字段扩展":
                    style["expend"]=ff.fieldName
                    break
            }
        })
        return style
    }

    const Valuekey=(index,value,key)=>{
        //console.log(index,value,key);
        form.value[key][index][value]=arr.value[index].value
    // console.log(form.value);
    }
    const inputValue = (index,value,key)=>{
        form.value[key][index][arr.value[index].key]=arr.value[index].value
    }
    const formSave =() =>{
        let data = XEUtils.clone(form.value,true)
        let ruler = true
        formData.value[form.value[filterType.value.field]].forEach((item)=>{
            if(fieldsContrast.value[item[Style.value.field]]['required']==true&&!data[item[Style.value.field]]){
                console.log(data[item[Style.value.field]]);
                ruler = false
            }
        })
        if(!ruler){
            ElMessage.error('必填项未填写')
            return
        }
        if(data){
            XEUtils.objectEach(data,(item,key)=>{
                if(XEUtils.isArray(item)){
                    let str =[];
                    XEUtils.arrayEach(item,it=>{
                        XEUtils.objectEach(it,(v,k)=>{
                            str.push(k+":"+v)
                        })
                    })
                    data[key]=str.join(",")
                }
            })

        }
        data['StatusCode']=0
        let m={}
        
        m[TM['MD']]=data
        // console.log(data)
        editForm(TM['CODE'],0, {D:{},M:m,T:TM['ID']}).then((res)=>{
            if(res.code===0){
            router.push('/form/'+TM['CODE'])
            }
        })
    }
</script>